<template>
  <el-dialog :close-on-click-modal='false' title="商品" :visible.sync="dialogFormVisible" :before-close="cancel">
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品标题：" prop="productName">
            <el-input v-model="form.productName" placeholder="请输入商品标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品分类：" prop="productTypeId">
            <el-select v-model="form.productTypeId" filterable clearable placeholder="请选择商品分类">
              <el-option v-for="item in productTypeList" :key="item.productTypeId" :label="item.productTypeName"
                :value="item.productTypeId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品价格：" prop="price">
            <el-input type="number" v-model.trim="form.price" placeholder="请输入商品价格"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品品牌：" prop="brand">
            <el-input v-model="form.brand" placeholder="请输入商品品牌"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品型号：" prop="model">
            <el-input v-model="form.model" placeholder="请输入商品型号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="12">
              <el-form-item label="商品规格：" prop="baseValue">
                <el-input v-model.trim="form.baseValue" type="number" placeholder="商品规格" />
              </el-form-item>
            </el-col>
            <el-col class="unit" :span="6">
              <el-form-item prop="baseUnitId">
                <el-select v-model="form.baseUnitId" filterable clearable placeholder="基础单位">
                  <el-option v-for="item in unitList" :key="item.unitId" :disabled="item.unitId == form.auxUnitId"
                    :label="item.unitName" :value="item.unitId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col class="unit" :span="6">
              <el-form-item prop="auxUnitId">
                <el-select v-model="form.auxUnitId" filterable clearable placeholder="辅助单位">
                  <el-option v-for="item in unitList" :key="item.unitId" :disabled="item.unitId == form.baseUnitId"
                    :label="item.unitName" :value="item.unitId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="规格描述:" class="flex" style="font-size: 0;">
            <el-input v-model="form.specDesc" type="string" clearable placeholder="例：请以实际规格为准" style="width:60%" />
            <el-select v-model="form.specDescDisplay" clearable placeholder="" style="width:30%">
              <el-option label="展示" :value="true"></el-option>
              <el-option label="不展示" :value="false"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品介绍：" prop="productDescription">
            <el-input type="textarea" v-model="form.productDescription" placeholder="请输入商品介绍"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品图片：" prop="fileList">
            <el-upload ref="upload" action="" :file-list="form.fileList" list-type="picture-card" :auto-upload="false"
              :on-change="handleChangeUpload" :on-remove="handleRemove" accept=".png,.jpg,.jpeg">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :close-on-click-modal='false' :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            <div style="font-size: 12px; color: #409EFF;">请上传.png,.jpg,.jpeg格式的图片，且图片大小不得超过2M</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 配送方式(0:线下自提 1:商家配送 2:线下自提和|商家配送),示例值(0) -->
          <el-form-item label="配送方式：" prop="deliveryMethod">
            <el-select v-model="form.deliveryMethod" filterable clearable placeholder="请选择配送方式">
              <el-option label='线下自提' :value="'0'"></el-option>
              <el-option label='商家配送' :value="'1'"></el-option>
              <el-option label='线下自提/商家配送' :value="'2'"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.deliveryMethod !== '1'" :span="12">
          <el-form-item label="自提点：" prop="pickupList">
            <el-select v-model="form.pickupList" filterable clearable multiple collapse-tags placeholder="请选择自提点">
              <el-option v-for="item, index in pickupPointList" :key="index"
                :label="item.pickupPointName ? item.pickupPointName : ''" :value="item.pickupPointId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import fileApi from '@/api/module/file'
import AgriculturalInfoManagement from '@/api/module/agricultural-info-management' //商品分类
import UnitsManagement from '@/api/module/units-management' //单位
import PickupLocationManagement from '@/api/module/pickup-location-management' //自提点
import config from '@/api/config'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      required: false
    },
    api: {
      type: Function,
      required: true
    }
  },
  data () {
    return {
      dialogImageUrl: '',
      disabled: false,
      dialogVisible: false,
      dialogFormVisible: false,
      rules: {
        fileList: [
          { required: true, message: '请上传商品图', trigger: 'blur' }
        ],//商品图片
        pickupList: [
          { required: true, message: '请选择自提点', trigger: 'change' }
        ], //自提点集合
        deliveryMethod: [
          { required: true, message: '请选择配送方式', trigger: 'blur' }
        ], //配送方式
        productDescription: [
          { required: true, message: '请输入商品介绍', trigger: 'blur' }
        ], //商品介绍
        baseValue: [
          { required: true, message: '请输入规格', trigger: 'blur' },
          {
            validator (_, value, callback) {
              if (value <= 0) {
                callback(new Error('商品规格不小于0'))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ], //基础单位对应值
        baseUnitId: [
          { required: true, message: '请输入基础单位', trigger: 'change' }
        ],//基础单位id
        auxUnitId: [
          { required: true, message: '请输入辅助单位', trigger: 'change' }
        ], //辅助单位id
        model: [
          { required: true, message: '请输入型号', trigger: 'blur' }
        ], //型号
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ], //商品
        productTypeId: [
          { required: true, message: '请选择商品类别', trigger: 'change' }
        ], //商品分类id
        price: [
          { required: true, message: '请输入商品价格', trigger: 'change' },
          {
            validator (_, value, callback) {
              if (value <= 0) {
                callback(new Error('商品价格不小于0'))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],//商品价格
        brand: [
          { required: true, message: '请输入商品品牌', trigger: 'blur' }
        ], //品牌
      },
      productTypeList: [],
      unitList: [],
      pickupPointList: [],
      form: {
        fileList: [],
        status: '1',
        pickupList: [],
        pickupPointIdList: '', //自提点集合
        deliveryMethod: '0', //配送方式  0=>自提  1=>配送
        productDescription: '', //商品介绍
        baseValue: '', //基础单位对应值
        baseUnitId: '',//基础单位id
        auxUnitId: '', //辅助单位id
        model: '', //型号
        productName: '', //商品
        productTypeId: '', //商品分类id
        price: '',//商品价格
        brand: '', //品牌
        imgList: []
      },
    };
  },
  watch: {
    showDialog: {
      handler (v) {
        this.dialogFormVisible = v
        v && (this.form = { ...this.form, ...this.formData }) && this.getFormData()
        v && (this.form.pickupList = this.form.pickupPointIdList ? this.form.pickupPointIdList.split(',').map(Number) : [])
        v && (this.form.productTypeId = this.form.productType ? this.form.productType.productTypeId : '')
        this.form.fileList = []
        if (this.form.imgList.length > 0) {
          this.form.imgList.forEach(imgObj => {
            this.form.fileList.push({
              name: '',
              url: imgObj.imgUrl
            })
          })
        }
      }
    },
    // 'form.fileList' (v) {
    //   console.log(v)
    //   if (v && v.length > 0) {
    //     this.$refs.form && this.$refs.form.clearValidate('fileList')
    //   }
    // }
  },
  methods: {
    handleRemove (file, fileList) {
      if (!file.raw) {
        this.form.fileList = this.form.fileList.filter(item => { return item.url !== file.url })
        this.form.imgList = this.form.imgList.filter(item => { return item.imgUrl !== file.url })
      } else {
        this.form.fileList = fileList
      }
    },
    handleChangeUpload (file, fileList) {
      console.log(this.$refs.upload)
      this.$refs.upload.clearFiles()
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        fileList.pop()
        this.form.fileList = fileList
      } else {
        this.form.fileList = fileList
      }
    },
    //获取表单下拉数据
    getFormData () {
      Promise.all([
        UnitsManagement.queryByCondition({}),  //商品单位
        AgriculturalInfoManagement.queryByCondition({}), //商品分类
        PickupLocationManagement.queryByCondition({})  //自提点
      ]).then(res => {
        this.unitList = res[0].data
        this.productTypeList = res[1].data
        this.pickupPointList = res[2].data
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '数据请求错误!'
        });
      })
    },
    //关闭 isRef是否刷新表单
    close (isRef) {
      this.$emit('closeDialog', isRef)
      this.$refs.form.resetFields()
    },
    //取消
    cancel () {
      this.form = {
        status: '1',
        pickupList: [],
        fileList: [],
        imgList: [],
        pickupPointIdList: '', //自提点集合
        deliveryMethod: '0', //配送方式  0=>自提  1=>配送  2=>自提/配送
        productDescription: '', //商品介绍
        baseValue: '', //基础单位对应值
        baseUnitId: '',//基础单位id
        auxUnitId: '', //辅助单位id
        model: '', //型号
        productName: '', //商品
        productTypeId: '', //商品分类id
        price: '',//商品价格
        brand: '', //品牌
      }
      this.close()
    },
    //获取上传文件的id
    async getFileId () {
      let promisesList = []
      let dataList = []
      this.form.fileList.forEach(item => {
        if (item.raw) {
          let fd = new FormData();
          console.log(item)
          fd.append("file", item.raw)
          console.log(fd, 'fd')
          promisesList.push(fileApi.fileUpload({
            fd, moduleType: 'SCIENCE_ARTICLE'
          }))
        }
      })
      await Promise.all(promisesList).then(resList => {
        resList.forEach(res => {
          dataList.push(res.data)
        })
      }).catch(err => {
        console.log('出错了', err)
      });
      return dataList
    },
    //确认
    confirm () {
      this.$refs.form.validate(async (valid) => {
        delete this.form.baseUnit
        delete this.form.auxUnit
        if (valid) {
          let getFileList = await this.getFileId()
          !this.form.imgList && (this.form.imgList = [])
          getFileList.forEach(data => {
            this.form.imgList.push({ imgUrl: config.webServiceUrl + '/ftp/file/download?fileId=' + data.fileId, productId: this.form.productId })
          })
          //  this.api 添加编辑接口 （注意传参）
          this.form.pickupPointIdList = this.form.pickupList.join(',')
          this.api(this.form).then(res => {
            console.log(res)
            if (res.code == 200) {
              this.form.fileList = [];
              this.form.imgList = [];
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.cancel()
              this.close(true)
            } else {
              this.$message({
                type: 'info',
                message: res.msg || '操作失败!'
              });
            }
          })
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}

::v-deep .unit .el-form-item__content {
  margin-left: 0 !important;
}
</style>